package com.baosight.sczx.zm.cc.service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiColumn;
import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.threadlocal.UserSession;
import com.baosight.iplat4j.ep.ServiceEPBase;
import com.baosight.sczx.common.StaticBlocks;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.Department;
import com.baosight.sczx.common.zm.cInterface.cs.InitialData;
import com.baosight.sczx.zm.cc.domain.ZMCCProduceproblem;
import com.baosight.sczx.zm.cs.domain.ZMCSInitialDataDetails;

/**
 * 生产问题录入
 * <p>Title: ServiceZMCC00.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 严洪浩
 * @version 1.0
 * <pre>Histroy:
 *          2011-6-27 上午08:01:23  严洪浩  Create
 *</pre>
 */
public class ServiceZMCC00 extends ServiceEPBase {
	/**
	 * 初始进入方法
	 * <p>Function: initLoad</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCC00</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2013-6-25 上午14:37:20 王开兵
	 * </p>
	 *
	 */
	@Override
	public EiInfo initLoad(EiInfo inInfo) 
	{
		inInfo.addBlock(EiConstant.resultBlock).set("showCount", "true");//如果不加这个，翻页的统计和显示是错误的
		EiInfo outInfo = this.query(inInfo);
		return outInfo;
	}
	
	/**
	 * 查询方法
	 * <p>Function: query</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCC00</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2013-6-25 上午14:47:20 王开兵
	 * </p>
	 *
	 */
	@Override
	public EiInfo query(EiInfo inInfo) 
	{
		//供生产实绩模块 调用
		// String fdForeignId = inInfo.getString("keyId");
		String miningCode = inInfo.getString("MiningId");	// 矿井id	
		String fdPlanYear = inInfo.getString("fdPlanYear");	// 年
		String fdPlanMonth = inInfo.getString("fdPlanMonth");	// 月
		String fdProblemType = inInfo.getString("fdProblemType"); //问题类型
		if(fdProblemType != null){
			try {
				fdProblemType = URLDecoder.decode(fdProblemType, "UTF-8");
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} //生产问题类型
		}
			
		String fdProblemTypeId = null;
		Map<String, String> _map = new HashMap<String, String>();
		_map.put("fdName", fdProblemType);
		List <ZMCSInitialDataDetails>typeList = dao.query("ZMCSInitialDataDetails.queryForProblem", _map);
		if(typeList.size()>0){
			fdProblemTypeId = typeList.get(0).getFdKeyId();
		}


		if (fdPlanYear != null && fdPlanMonth != null && fdProblemTypeId != null) {
			String fdBeginDate = this.getFirDay(fdPlanYear, fdPlanMonth);
			String fdEndDate = StaticTools.getLastDay(fdBeginDate);
			StaticTools.setQueryParameters(inInfo, "fdBeginDate", fdBeginDate, true);
			StaticTools.setQueryParameters(inInfo, "fdEndDate", fdEndDate, true);
			StaticTools.setQueryParameters(inInfo, "fdProblemTypeId", fdProblemTypeId, true);	
			StaticTools.setQueryParameters(inInfo, "isReported", "yes", true);// 所有已上报问题
		}
		if (miningCode == null) {
			if (null != UserSession.getInSessionProperty("miningCode")) {
				miningCode = UserSession.getInSessionProperty("miningCode").toString();
			}
		}
		StaticTools.setQueryParameters(inInfo, "fdMiningId", miningCode, true);
		EiInfo outInfo = super.query(inInfo, "ZMCCProduceproblem.query", new ZMCCProduceproblem());
		
//		ZMCCProduceproblem zmccProduceproblem = new ZMCCProduceproblem();
//		String miningCode = "";
//		if(null != UserSession.getInSessionProperty("miningCode")){
//			miningCode = UserSession.getInSessionProperty("miningCode").toString();
//			zmccProduceproblem.setFdMiningId(miningCode);
//		}
		
//		outInfo.addBlock(getMines());
		
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cp.problemType", false));//问题类型
		outInfo.addBlock(StaticBlocks.getProblemStatus());//问题状态
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cp.problemLevel",false));//问题级别
		outInfo.addBlock(StaticBlocks.getIsCheck());//是否核查
//		outInfo.addBlock(StaticBlocks.getProblemOrigin());//问题来源
		outInfo.addBlock(InitialData.getInstance().getEiBlockByNo("cmes.cp.problemOrigin"));//问题来源 
//		outInfo.addBlock(Department.getInstance().getConstructionUnit("cmes.cp.department", "orgCode", "orgName", false));
		
		outInfo.addBlock(Department.getInstance().getMiningDepts("cmes.cp.department", "orgCode", "orgName", false,UserSession.getInSessionProperty("miningCode").toString()));//责任部门
		
		outInfo.set("fdCreatorId", UserSession.getUserId());//登录人的默认值
		outInfo.set("fdCreator", UserSession.getInSessionProperty("UserCname"));
		outInfo.set("fdCreateDepartmentId", UserSession.getInSessionProperty("orgCode"));//单位的默认值		
		outInfo.set("fdCreateDepartment", UserSession.getInSessionProperty("orgName"));//单位的默认值
		outInfo.set("fdMiningId",miningCode);//矿ID的默认值
		outInfo.set("fdMiningName", UserSession.getInSessionProperty("miningName"));//矿名称的默认值
		
		return outInfo;
	}
	
	public EiBlock getMines() {
		EiBlock block = new EiBlock("cmes.ch.mine");

		EiColumn EiColumn = new EiColumn("display");
		EiColumn.setType("C");
		block.addMeta(EiColumn);

		EiColumn = new EiColumn("value");
		EiColumn.setType("C");
		block.addMeta(EiColumn);

		List<Map> _list = new ArrayList<Map>();
		Map<String, String> _map = new HashMap<String, String>();
		_map.put("value", "");
		_map.put("display", "");
		_list.add(_map);

		List<Map> _listData = new ArrayList<Map>();
		try {
			_listData = dao.query("ZMCCProduceproblem.queryTreeChild", null);
		} catch (Exception e) {}
		
		for(int i = 0; i < _listData.size(); i++) {
			_list.add(_listData.get(i)); 
		} 
		block.setRows(_list);
		return block;
	}
	
	/**
	 * 新增方法
	 * <p>Function: insert</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCBCoalseam</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2013-6-25上午11:34:17 王开兵
	 * </p>
	 *
	 */
	@Override
	public EiInfo insert(EiInfo inInfo) 
	{
		EiInfo out=new EiInfo(); 
		ZMCCProduceproblem _dom = new ZMCCProduceproblem();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		int i = 0;
		for (; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			//校验是否重复
			Map<String, String> params = new HashMap<String, String>();
			params.put("fdKeyId", _dom.getFdKeyId());

			_dom.setFdKeyId(TablePk.getInstance().getNextValue("T_CC_PRODUCEPROBLEM"));
			_dom.setFdProblemStatus("0"); 	// 生产问题状态设为草拟
			if(null != UserSession.getInSessionProperty("miningCode")){
				_dom.setFdMiningId(UserSession.getInSessionProperty("miningCode").toString());
			}
			_dom.setFdCreateUserId(UserSession.getUserId().toString());
//			_dom.setFdSubmitorId(UserSession.getUserId().toString());
			_dom.setFdCreateUser(UserSession.getInSessionProperty("UserCname") == null ? "" : UserSession.getInSessionProperty("UserCname").toString());
//			_dom.setFdSubmitor(UserSession.getInSessionProperty("UserCname") == null ? "" : UserSession.getInSessionProperty("UserCname").toString());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			_dom.setFdCreateTime(sdf.format(new Date()));
			_dom.setFdSubmitorDepartment(Department.getInstance().getDepartmentNameById(_dom.getFdSubmitorDepartmentId()));
		    this.dao.insert("ZMCCProduceproblem.insert", _dom);
			
		}
		out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作" + rowcount + "记录成功");
		return out; 		
				
	}

	/**
	 * 修改方法
	 * <p>Function: update</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCBCoalseam</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2013-6-24上午13:34:17 王开兵
	 * </p>
	 *
	 */
	@Override
	public EiInfo update(EiInfo inInfo) 
	{
		EiInfo out=new EiInfo();
		ZMCCProduceproblem _dom = new ZMCCProduceproblem();
		EiBlock eiBlock = inInfo.getBlock("result");
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		int i = 0;
		for (; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			//校验是否重复
//			Map<String, String> params = new HashMap<String, String>();
//			params.put("fdKeyId", _dom.getFdKeyId());
//			boolean validate = this.validate(inInfo, _dom, params);
//			if(validate) {
//				return inInfo;
//			} 
			_dom.setFdSubmitorDepartment(Department.getInstance().getDepartmentNameById(_dom.getFdSubmitorDepartmentId()));
		    this.dao.update("ZMCCProduceproblem.update", _dom);			
		}
		out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作" + rowcount + "记录成功");
		return out; 		
		
		
		
}
	
	/**
	 * 删除方法
	 * <p>Function: delete</p>
	 * <p>Description: </p>
	 * <p>return value: ServiceZMCBCoalseam</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2013-6-26上午13:34:17 王开兵
	 * </p>
	 *
	 */
	@Override
	public EiInfo delete(EiInfo inInfo) 
	{

		EiInfo outInfo = null;
		
//		List<String> _list = new ArrayList<String>();
//		Map<String,List<String>> params = new HashMap<String,List<String>>();

		for(int i = 0; i < inInfo.getBlock(EiConstant.resultBlock).getRowCount(); i++)
		{

			EiInfo _temp = super.delete(inInfo, "ZMCCProduceproblem.delete");
	        outInfo = this.query(inInfo);
	        outInfo.setMsg(_temp.getMsg());
	        outInfo.setDetailMsg(_temp.getDetailMsg());
		}
		
		return outInfo;
	}
	
	/**
	 * 上报
	 * <p>Function: report</p>
	 * <p>Description: </p>
	 * <p>return value:EiInfo</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-7-6下午04:07:27 张志芳
	 * </p>
	 *
	 */
	public EiInfo report(EiInfo inInfo)
	{
		EiInfo out=new EiInfo(); 
		ZMCCProduceproblem _dom = new ZMCCProduceproblem();
		EiBlock eiBlock = inInfo.getBlock("result");
		
		eiBlock.setBlockMeta(_dom.eiMetadata);
		int rowcount = eiBlock.getRowCount();
		int i = 0;
		for (; i < rowcount; i++) {
			_dom.fromMap(eiBlock.getRow(i));
			
			Map<String, String> params = new HashMap<String, String>();
			params.put("fdKeyId", _dom.getFdKeyId());

			this.dao.update("ZMCCProduceproblem.report",_dom);
		}	
		out = this.query(inInfo);
		out.setStatus(1);
		out.setMsg("操作" + rowcount + "记录成功");
		return out;   
	
	}
	
	/**
	 * 
	 * <p>Function: getFirDay</p>
	 * <p>Description: 根据传入的年份、月份，获取当月第一天日期</p>
	 * <p>return value:String</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2016年7月28日下午4:54:39 郭淑芳
	 * </p>
	 *
	 */
	private String getFirDay(String yearStr, String monthStr) {
		if (monthStr.trim().length() < 2) {
			monthStr = yearStr.trim() + "-0" + monthStr.trim() + "-01";
		} else {
			monthStr = yearStr.trim() + "-" + monthStr.trim() + "-01";
		}
		return monthStr;
	}
}
